<!--
@fucntion: 医用耗材基本信息
-->
<template>
<div class="module-basic-Consumables">
  <el-row style="height:100%;">
    <el-col style="height:100%;">
      <table-panel
      v-show="SwitchingPoint"
      :name="'医用耗材基本信息'"
      :columns="ConsumablesColumns"
      :tableData="ConsumablesData"
      :showRowNumber="false"
      :multiSelection="true"
      :inputLabelSearchMode="true"
      :canCreate="authority.create"
      :canMultiDelete="authority.multiDelete"
      :canEdit="authority.edit"
      :canDelete="authority.delete"
      :canExport="authority.export"
      :canImport="authority.import"
      :action="actionUrl"
      :importFields="importField"
      @table-upload="onUpload"
      :currentPage="currentPage"
      :totalNum="totalNum"
      :canDownTemplate="authority.downTemplate"
      @page-change="onPageChange"
      :pageSize="pageSize"
      @table-searching="onSearching('Consumables',$event)"
      @table-create="onCreate('Consumables',$event)"
      @table-multi-delete="onMultiDelete('Consumables',$event)"
      @table-edit="onEdit('Consumables', $event)"
      @table-delete="onDelete('Consumables',$event)"
      @table-export="onExport('Consumables',$event)"
      @table-downTemplate="onDownTemplate('Consumables',$event)"
      @selection-change="onSelectionChange('Consumables',$event)">
      </table-panel>

      <el-col v-show="!SwitchingPoint">
        <el-card style="background-color: #DCDFE6;">
          <span v-if="(Ddata)" style="font-weight:bold;">医用耗材信息添加</span>
          <span v-else style="font-weight:bold;">医用耗材信息修改</span>
          <el-button type="warning" plain size="mini" style="float:right"
            @click="onConfirm('Consumables')">
            <span v-if="(Ddata)" style="font-weight:bold;">确认添加</span>
            <span v-else style="font-weight:bold;">确认修改</span>
          </el-button>
          <el-button v-if="(Ddata)" type="danger"  plain size="mini" style="float:right"
            @click="ConsumablesRecord = {};">重置</el-button>
          <el-button plain size="mini" style="float:right"
            @click="SwitchingPoint = !(SwitchingPoint);">返回
          </el-button>
        </el-card>

        <el-form ref="ConsumablesRecord"
        :model="ConsumablesRecord"
        :rules="ConsumablesRules"
        label-position="right"
        label-width="105px"
        size="mini"
        status-icon>
        <el-card style="width: 100%;height:600px;">
          <el-card>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="自定义编号" prop="medicalConsumableDefinedId">
                  <el-input  v-model="ConsumablesRecord.medicalConsumableDefinedId"></el-input>
                </el-form-item>
                <el-form-item label="耗材名称" prop="medicalConsumableName">
                  <el-input  v-model="ConsumablesRecord.medicalConsumableName"></el-input>
                </el-form-item>
                <el-form-item label="规格型号" prop="specifications">
                  <el-input  v-model="ConsumablesRecord.specifications"></el-input>
                </el-form-item>
                <el-form-item label="单位" prop="unit">
                  <el-input  v-model="ConsumablesRecord.unit"></el-input>
                </el-form-item>
                <el-form-item label="单价" prop="price">
                  <el-input  v-model="ConsumablesRecord.price"><template slot="append">{{ConsumablesRecord.unit}}</template></el-input>
                </el-form-item>
                <el-form-item label="合同号" prop="contractNo">
                  <el-input  v-model="ConsumablesRecord.contractNo"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="供应商名称" prop="providerName">
                  <el-select v-model="ConsumablesRecord.providerName" placeholder="请输入或查找选择供应商" filterable clearable>
                    <el-option
                      v-for="(item,index) in XLdata.data_providerName"
                      :key="index"
                      :label="item.data"
                      :value="item.value">
                      <span style="float: left">{{ item.data }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="生产厂家" prop="productionPlace">
                  <el-input  v-model="ConsumablesRecord.productionPlace"></el-input>
                </el-form-item>
                <el-form-item label="物资类别" prop="suppliesCategory">
                  <el-select v-model="ConsumablesRecord.suppliesCategory" placeholder="请选择类别">
                    <el-option
                      v-for="(item,index) in XLdata.data_suppliesCategory"
                      :key="index"
                      :label="item.data"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="会计科目" prop="accountTitle">
                  <el-select v-model="ConsumablesRecord.accountTitle" placeholder="请选择会计科目">
                    <el-option
                      v-for="(item,index) in XLdata.data_accountTitle"
                      :key="index"
                      :label="item.data"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="耗材使用" prop="medicalConsumableUsing">
                  <el-input  v-model="ConsumablesRecord.medicalConsumableUsing" maxlength="2" @keyup.native="handleInput"><template slot="append">%</template></el-input>
                </el-form-item>
                <el-form-item label="收入项目" prop="entitlementSpending">
                  <el-input  v-model="ConsumablesRecord.entitlementSpending"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="国产进口" prop="domesticImports">
                  <el-select v-model="ConsumablesRecord.domesticImports" placeholder="请选择">
                    <el-option label="国产" value="国产"></el-option>
                    <el-option label="进口" value="进口"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="是否代销" prop="sale">
                  <el-switch
                    v-model="ConsumablesRecord.sale"
                    :active-value="1"
                    :inactive-value="0"
                  >
                  </el-switch>
                </el-form-item>
                <el-form-item label="是否高值" prop="highValueConsumables">
                  <el-switch
                    v-model="ConsumablesRecord.highValueConsumables"
                    :active-value="1"
                    :inactive-value="0"
                  >
                  </el-switch>
                </el-form-item>
                <el-form-item label="是否收费" prop="charge">
                  <el-switch
                    v-model="ConsumablesRecord.charge"
                    :active-value="1"
                    :inactive-value="0"
                  >
                  </el-switch>
                </el-form-item>
                <el-form-item label="备注" prop="notes">
                  <el-input
                    type="textarea"
                    :autosize="{ minRows:2 , maxRows: 5}"
                    placeholder="请输入内容"
                    maxlength="50"
                    show-word-limit
                    v-model="ConsumablesRecord.notes">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-card>
        </el-form>
      </el-col>
    </el-col>
  </el-row>
</div>
</template>

<script>
import TablePanel from "@/components/basic/TablePanel";//一个简单的增删查改表格
import {
  formModelInitFromTable,
  formRulesInitFromTable
} from "@/utils/formutils.js";//从表格列变换到表单的一些工具

//meta info
var tableName = "Consumables"; // 表格名称
//var Consumables = "Consumables"; // 表格名称
var columnsPrefix = "Columns"; // 列
var dataPrefix = "Data"; // 数据
var selectionAttr = "Selection"; // 选中
var dlgVisiblePrefix = "DlgVisible"; // 对话框
var formPrefix = "Form";
var recordPrefix = "Record"; // 表单模型
var rulesPrefix = "Rules";// 表单验证
//var curPageAttr = "CurrentPage";// 分页-当前页
var qParamAttr = "QueryParams";// 查询参数

// 采集器信息-列
var ConsumablesColumns = [
  {
    prop: "medicalConsumableId",
    label: "编号",
    outOfSearch:true,
    hidden: true,
  },
  {
    prop: "medicalConsumableDefinedId",
    label: "自定编号",
    width:80,
    rules: [
      { required: true, message: '请输入自定义编号', trigger: 'blur' },
      { min: 1, max: 15, message: '长度最大为15个字符', trigger: 'blur' }
    ]
  },
  {
    prop: "medicalConsumableName",
    label: "耗材名称",
    width:150,
    rules: [
      { required: true, message: '请输入耗材名称', trigger: 'blur' },
      { min: 1, max: 50, message: '长度最大为50个字符', trigger: 'blur' }
    ]
  },
  {
    prop: "specifications",
    label: "规格型号",
    width:100,
    rules: [
      { required: true, message: '请输入规格型号', trigger: 'blur' },
      { min: 1, max: 100, message: '长度最大为100个字符', trigger: 'blur' }
    ]
  },
  {
    prop: "productionPlace",
    label: "生产厂家",
    width:150,
    rules: [
      { required: true, message: '请输入生产厂家', trigger: 'blur' },
      { min: 1, max: 50, message: '长度最大为50个字符', trigger: 'blur' }
    ]
  },
  {
    prop: "price",
    label: "单价",
    outOfSearch:true,
    rules: [
      { required: true, message: '请输入单价', trigger: 'blur' }
    ]
  },
  {
    prop: "unit",
    label: "单位",
    outOfSearch:true,
    width:60,
    rules: [
      { required: true, message: '请输入单位', trigger: 'blur' },
      { min: 1, max: 5, message: '长度最大为5个字符', trigger: 'blur' }
    ]
  },
  {
    prop: "entitlementSpending",
    label: "收入项目",
    outOfSearch:true,
  },
  {
    prop: "providerId",
    label: "供应商编码",
    outOfSearch:true,
    width:95,
  },
  {
    prop: "providerName",
    label: "供应商名称",
    outOfSearch:true,
    width:150,
  },
  {
    prop: "suppliesCategory",
    label: "物资类别",
  },
  {
    prop: "accountTitle",
    label: "会计科目",
    width:120,
  },
  {
    prop: "domesticImports",
    label: "国产进口",
  },
  {
    prop: "contractNo",
    label: "合同号",
    width:130,
    rules: [
      { required: true, message: '请填写合同号', trigger: 'blur' },
      { min: 1, max: 15, message: '长度最大为15个字符', trigger: 'blur' }
    ]
  },
  {
    prop: "highValueConsumables",
    label: "是否高值",
    outOfSearch:true,
    hidden: true,
  },
  {
    prop: "charge",
    label: "是否收费",
    outOfSearch:true,
    hidden: true,
  },
  {
    prop: "sale",
    label: "是否代销",
    outOfSearch:true,
    hidden: true,
  },
  {
    prop: "notes",
    label: "备注",
    outOfSearch:true,
    hidden: true,
  },
  {
    prop: "medicalConsumableUsing",
    label: "耗材使用",
  }
];

//导入
var importField = [
  "编号",
  "编号自定义",
  "耗材名称",
  "规格型号",
  "生产厂家",
  "单价",
  "单位",
  "收入项目",
  "供应商编码",
  "供应商名称",
  "物资类别",
  "会计科目",
  "国产进口",
  "合同号",
  "是否高值",
  "是否收费",
  "是否代销",
  "备注",
  "耗材使用",
];
//导出
var exportField = [
  "编号",
  "编号自定义",
  "耗材名称",
  "规格型号",
  "生产厂家",
  "单价",
  "单位",
  "收入项目",
  "供应商编码",
  "供应商名称",
  "物资类别",
  "会计科目",
  "国产进口",
  "合同号",
  "是否高值",
  "是否收费",
  "是否代销",
  "备注",
  "耗材使用",
];

export default {
  //name: "Consumables",
  components: {
    "table-panel": TablePanel,
  },
  methods: {
    // 查询
    onSearching: function(tableName, params) {
      let me = this;
      me.loading = true;
      me.queryParams = {};
      me.queryParams = params;
      if (params.isAccurate) {
        me.queryParams = params.paramPairs;
      } else {
        me.queryParams.keywords = params.query;
      }
      me.currentPage = 1;
      me.queryParams.page = me.currentPage;
      me.getRequest("/Consumable", me.queryParams).then(resp => {
        me.loading = false;
        if (resp.status == 200) {
          me[tableName + dataPrefix] = resp.data.results;
          me.totalNum = resp.data.total;
        }
      });
    },
    onCreate: function(tableName) {// 新增
      let me = this;
      me[tableName+dlgVisiblePrefix] = true;
      me[tableName+recordPrefix] = formModelInitFromTable(me[tableName+columnsPrefix]);
      me.ConsumablesRecord = {};
      me.Ddata = true;
      me.SwitchingPoint = !(me.SwitchingPoint);
    },
    onEdit: function(tableName, row) {// 编辑
      let me = this;
      me[tableName + dlgVisiblePrefix] = true;
      me[tableName + recordPrefix] = row;
      me.Ddata = false;
      me.SwitchingPoint = !(me.SwitchingPoint);
      me.ConsumablesRecord = row
    },
    onDelete: function(tableName, row) {// 删除
      var me = this;
      me.$confirm("确定删除这条记录吗?", "提示", {
          type: "warning"
      }).then(() => {
          me.deleteRequest(`/Consumable/${row.medicalConsumableId}`).then((resp)=>{
            if(resp.status == 200) {
              me.$message.success("删除成功!");
              me.loading = true;
              me.getRequest("/Consumable",me.queryParams).then(resp => {
                me.loading = false;
                if (resp.status == 200) {
                  me[tableName + dataPrefix] = resp.data.results;
                  me.totalNum = resp.data.total;
                }
              });
            }else{
              me.$message.error('删除失败！');
            }
          });
      }).catch(() => {});
    },
    onMultiDelete:function(tableName, row){//全部删除
      var me = this;
      me.$confirm("确定删除全部记录吗?", "提示", {
          type: "warning"
      }).then(() => {
          me.deleteRequest(`/api`).then((resp)=>{
            if(resp.status == 200) {
              me.$message.success("删除成功!");
              me.onSearching(Charges,{});// 重新加载表格数据
            }else{
              me.$message.error('删除失败！');
            }
          });
      }).catch(() => {});
    },
    onSelectionChange: function(tableName, data) {// 选中改变
      var me = this;
      // 缓存记录，按照编号，查询对应的选中权限节点数组
      me[tableName + selectionAttr] = data;
    },
    onExport: function(tableName, params) {// 导出
      var me = this;
      const h = me.$createElement;
      me.$notify.info({
        title: "提示",
        message: h("i", { style: "color: teal" }, "正在导出数据，请稍等……")
      });
      me.exportRequest("/sbxxgl/export", {
        fields: JSON.stringify(exportField),//exportField
        sfbf: false
      }).then(resp => {
        if (resp.status === 200) {
          me.$notify.success({
            title: "提示",
            message: h("i", { style: "color: #67C23A" }, "数据导出成功")
          });
          downExcel(resp);
        } else {
          me.$notify.success({
            title: "提示",
            message: h("i", { style: "color: #F56C6C" }, "数据导出失败")
          });
        }
      });
    },
    onUpload:function(msg,flag){//导入
      var me = this;
      if(flag){
        me.currentPage = 1;
        me.onSearching('sbxxgl',{page:me.currentPage,size:me.pageSize});
      }
    },
    onDownTemplate:function(tableName, params){//模板下载
      var me = this;
      const h = me.$createElement;
      me.$notify.info({
        title: '提示',
        message: h('i', { style: 'color: teal'}, '正在下载模板，请稍等……')
      });
      me.downFileRequest('/excelTemplate/医用耗材基本信息.xlsx').then(resp=>{
        me.$notify.success({
          title: '提示',
          message: h('i', { style: 'color: #67C23A'}, '模板下载成功')
        });
        fileDownload(resp.data,"医用耗材基本信息.xlsx");
      });
    },
    onPageChange:function(page){// 分页改变
      var me = this;
      me.loading = true;
      me.currentPage = page;
      me.queryParams["page"] = page;
      me.getRequest("/Consumable", me.queryParams).then(resp => {
        me.loading = false;
        if (resp.status == 200) {
          me[tableName + dataPrefix] = resp.data.results;
          me.totalNum = resp.data.total;
        }
      });
    },
    onConfirm: function() {// 对话框-确认
      let me = this;
      // // 验证信息
      // var ret;
      // me.$refs[tableName + formPrefix].validate((result, what) => {
      //   ret = result;
      // });
      // if (!ret) {
      //   me.$message({
      //     message: "表单信息有误",
      //     type: "error"
      //   });
      //   return;
      // }
      console.log(me[tableName + recordPrefix])
      console.log(me.ConsumablesRecord)
      // 发送请求 /jcJsxxb
      if(me[tableName + recordPrefix].medicalConsumableId == ""){

        me.$confirm("确定新增记录吗?", "提示", {
          type: "warning"
        }).then(() => {
          me.postRequest("/Consumable",me[tableName + recordPrefix]).then(resp => {
            if (resp.status == 200) {
              me.$message.success("提交成功！");

              //最后，隐藏对话框
              me[tableName + dlgVisiblePrefix] = false;
              me.SwitchingPoint = !(me.SwitchingPoint);
              me.onSearching(tableName, {});// 重新查一遍
            } else {
              me.$message.error("服务器发生错误，代码：" + resp.status);
            }
          });
        }).catch(() => {});
      }else{

        me.$confirm("确定修改记录吗?", "提示", {
          type: "warning"
        }).then(() => {
          me.postRequest("/Consumable",me[tableName + recordPrefix]).then(resp => {
            if (resp.status == 200) {
              me.$message.success("提交成功！");

              //最后，隐藏对话框
              me[tableName + dlgVisiblePrefix] = false;
              me.SwitchingPoint = !(me.SwitchingPoint);
              me.onSearching(tableName, {});// 重新查一遍
            } else {
              me.$message.error("服务器发生错误，代码：" + resp.status);
            }
          });
        }).catch(() => {});
      }
    },
    handleInput() {
      let me = this;
      me[tableName + recordPrefix].medicalConsumableUsing = me[tableName + recordPrefix].medicalConsumableUsing.replace(/[^\.\d]/g, '')
      me[tableName + recordPrefix].medicalConsumableUsing = me[tableName + recordPrefix].medicalConsumableUsing.replace('.', '')
    }
  },
  data() {
    return {
      authority:{
        create:true,
        deleteAll:true,
        delete:true,
        edit:true,
        search:true,
        export:true,
        import:true,
        downTemplate:true,
      },// 权限控制
      [tableName + columnsPrefix]: ConsumablesColumns, // 表格-列
      [tableName + dataPrefix]: [], // 表格的数据
      [tableName + selectionAttr]: [], // 当前选中
      [tableName + dlgVisiblePrefix]: false, // 对话框是否可见
      [tableName + recordPrefix]: {}, // 表单模型
      [tableName + rulesPrefix]: {},// 表单验证
      currentPage: 1,// 当前页
      // [Consumables + qParamAttr]:{},// 查询参数
      queryParams: {},
      pageSize:20,// 每页数量
      totalNum: 0,
      importField:importField.join(","),//导入的字段

      SwitchingPoint: true,//表单列表之间-切换控制

      ConsumablesRecord:{},//存储表单中的数据

      Ddata: true,//控制表单头标题的显示内容

      actionUrl:"/sbxxgl/import",//导入的路径

      XLdata:{
        data_suppliesCategory:{},//物资类别下拉
        data_accountTitle:{},//会计科目下拉
        data_providerName:{},//供应商名称下拉
      }
    };
  },
  created: function() {
    let me = this;
    // 添加权限控制
    // me.authority = me.$route.meta["authority"];
    // me.authorities = me.$route.meta.authorities;

    // 表单模型初始化
    me[tableName + recordPrefix] = formModelInitFromTable(me[tableName + columnsPrefix]);
    // 表单验证初始化
    me[tableName + rulesPrefix] = formRulesInitFromTable(me[tableName + columnsPrefix]);
    //物资类别下拉初始化
    me.getRequest("/static/data/data_BMMC.json",{}).then(resp=>{
      if(resp.status == 200) {
        me.XLdata.data_supplies_category = resp.data.data;
      }
    });
    //会计科目下拉初始化
    me.getRequest("/static/data/data_BMMC.json",{}).then(resp=>{
      if(resp.status == 200) {
        me.XLdata.data_account_title = resp.data.data;
      }
    });
    //供应商名称下拉初始化
    me.getRequest("/static/data/data_BMMC.json",{}).then(resp=>{
      if(resp.status == 200) {
        me.XLdata.data_provider_name = resp.data.data;
      }
    });
    me.onSearching(tableName, {});// 重新查一遍
  }
};
</script>

<style lang="scss">
.module-basic-Consumables {
  height: 100%;
}
</style>
